<template>
  <div class="student-form-page">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><EditPen /></el-icon>
            {{ isEdit ? '编辑学生信息' : '新增学生信息' }}
          </span>
          <el-button @click="handleBack">
            <el-icon><Back /></el-icon>
            返回
          </el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        style="max-width: 600px; margin: 20px auto"
      >
        <el-form-item label="学号" prop="studentId">
          <el-input
            v-model="form.studentId"
            placeholder="请输入学号（6-10位数字）"
            :disabled="isEdit"
            maxlength="10"
          >
            <template #prefix>
              <el-icon><Notebook /></el-icon>
            </template>
          </el-input>
          <div class="form-tip" v-if="!isEdit">
            学号由6-10位数字组成，创建后不可修改
          </div>
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入学生姓名"
            maxlength="20"
            show-word-limit
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="班级" prop="class">
          <el-autocomplete
            v-model="form.class"
            :fetch-suggestions="queryClasses"
            placeholder="请输入或选择班级"
            style="width: 100%"
          >
            <template #prefix>
              <el-icon><School /></el-icon>
            </template>
          </el-autocomplete>
          <div class="form-tip">
            可以直接输入新班级，或从历史班级中选择
          </div>
        </el-form-item>

        <el-form-item label="成绩" required>
          <div style="width: 100%">
            <div v-for="(course, index) in form.scores" :key="index" style="margin-bottom: 15px">
              <el-row :gutter="10">
                <el-col :span="10">
                  <el-input
                    v-model="course.courseName"
                    placeholder="课程名称（如：数学、语文）"
                    clearable
                  >
                    <template #prefix>
                      <el-icon><Reading /></el-icon>
                    </template>
                  </el-input>
                </el-col>
                <el-col :span="10">
                  <el-input-number
                    v-model="course.score"
                    :min="0"
                    :max="100"
                    :precision="1"
                    :step="0.5"
                    placeholder="成绩"
                    style="width: 100%"
                  />
                </el-col>
                <el-col :span="4">
                  <el-button
                    v-if="form.scores.length > 1"
                    type="danger"
                    :icon="Delete"
                    circle
                    @click="removeCourse(index)"
                  />
                  <el-button
                    v-if="index === form.scores.length - 1"
                    type="primary"
                    :icon="Plus"
                    circle
                    @click="addCourse"
                  />
                </el-col>
              </el-row>
            </div>
            <div class="form-tip">
              点击 + 号添加更多课程，每门课程成绩范围：0-100分
            </div>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="submitting"
            size="large"
            style="width: 120px"
          >
            {{ isEdit ? '保存修改' : '立即创建' }}
          </el-button>
          <el-button @click="handleReset" size="large" style="width: 120px">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Delete, Plus } from '@element-plus/icons-vue'
import { getStudent, createStudent, updateStudent, getClasses } from '@/api/student'

const router = useRouter()
const route = useRoute()
const formRef = ref()

// 判断是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 表单数据
const form = reactive({
  studentId: '',
  name: '',
  class: '',
  scores: [{ courseName: '', score: null }]
})

// 班级列表（用于自动完成）
const classList = ref([])

// 提交状态
const submitting = ref(false)

// 表单验证规则
const rules = {
  studentId: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { 
      pattern: /^[0-9]{6,10}$/, 
      message: '学号必须是6-10位数字', 
      trigger: 'blur' 
    }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在2-20个字符', trigger: 'blur' }
  ],
  class: [
    { required: true, message: '请输入班级', trigger: 'blur' }
  ]
}

// 加载学生详情（编辑模式）
const loadStudent = async () => {
  try {
    const res = await getStudent(route.params.id)
    Object.assign(form, res.data)
  } catch (error) {
    ElMessage.error('加载学生信息失败')
    router.back()
  }
}

// 加载班级列表
const loadClasses = async () => {
  try {
    const res = await getClasses()
    classList.value = res.data.map(cls => ({ value: cls }))
  } catch (error) {
    console.error('加载班级列表失败:', error)
  }
}

// 班级自动完成查询
const queryClasses = (queryString, cb) => {
  const results = queryString
    ? classList.value.filter(item => 
        item.value.toLowerCase().includes(queryString.toLowerCase())
      )
    : classList.value
  cb(results)
}

// 添加课程成绩
const addCourse = () => {
  form.scores.push({ courseName: '', score: null })
}

// 删除课程成绩
const removeCourse = (index) => {
  if (form.scores.length > 1) {
    form.scores.splice(index, 1)
  } else {
    ElMessage.warning('至少保留一门课程')
  }
}

// 验证课程成绩
const validateCourses = () => {
  // 过滤掉完全空白的课程行（课程名和成绩都为空）
  const validCourses = form.scores.filter(course => {
    const hasCourseName = course.courseName && course.courseName.trim() !== ''
    const hasScore = course.score !== null && course.score !== ''
    return hasCourseName || hasScore
  })

  // 至少需要一门课程
  if (validCourses.length === 0) {
    ElMessage.error('请至少添加一门课程及成绩')
    return false
  }

  // 验证每门课程的完整性
  for (let i = 0; i < validCourses.length; i++) {
    const course = validCourses[i]
    
    if (!course.courseName || course.courseName.trim() === '') {
      ElMessage.error('课程名称不能为空')
      return false
    }
    
    if (course.score === null || course.score === '') {
      ElMessage.error(`请输入${course.courseName}的成绩`)
      return false
    }
    
    if (course.score < 0 || course.score > 100) {
      ElMessage.error(`${course.courseName}成绩必须在0-100之间`)
      return false
    }
  }

  // 更新表单数据为有效的课程列表
  form.scores = validCourses
  
  return true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    // 验证课程成绩
    if (!validateCourses()) {
      return
    }

    submitting.value = true

    if (isEdit.value) {
      // 更新学生
      await updateStudent(route.params.id, {
        name: form.name,
        class: form.class,
        scores: form.scores
      })
      ElMessage.success('保存成功')
    } else {
      // 创建学生
      await createStudent(form)
      ElMessage.success('创建成功')
    }

    router.push('/students')
  } catch (error) {
    if (error.errors) {
      ElMessage.error('请检查表单填写是否正确')
    }
  } finally {
    submitting.value = false
  }
}

// 重置表单
const handleReset = () => {
  if (isEdit.value) {
    loadStudent()
  } else {
    formRef.value?.resetFields()
  }
}

// 返回
const handleBack = () => {
  router.back()
}

onMounted(() => {
  if (isEdit.value) {
    loadStudent()
  }
  loadClasses()
})
</script>

<style scoped>
.student-form-page {
  max-width: 900px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>
